﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OfficeOpenXml;

namespace ECMS.Infrastructure.Helper
{
    public class ExcelHelper<TBody, TWhere> where TBody : class
    {

        public static string Export(ExportRequestModel<TWhere> THead, List<TBody> TBody, string LocalPath)
        {
            try
            {
                string sFileName = $"{THead.ExportUserId}-{Guid.NewGuid()}.xlsx";
                var finallypath = LocalPath + "\\excel\\" + THead.ModuleName;
                DirectoryInfo di = new DirectoryInfo(finallypath);
                if (!di.Exists) { di.Create(); }
                FileInfo file = new FileInfo(Path.Combine(finallypath, sFileName));

                var pack = GetExcelPackage(THead.RowRequest, TBody);
                pack.SaveAs(file);

                return ("\\" + THead.ModuleName + "\\" + sFileName).Replace("\\", "/");
            }
            catch (Exception) 
            {
                throw;
            }


        }

        private static ExcelPackage GetExcelPackage(List<ExportRowModel> THead, List<TBody> TBody)
        {
            ExcelPackage package = new ExcelPackage();


            var worksheet = package.Workbook.Worksheets.Add("sheet1");
            //循环生成表头
            for (int i = 1; i <= THead.Count; i++)
            {
                worksheet.Cells[1, i].Value = THead[i - 1].RowName;
            }

            //循环值
            for (int i = 1; i <= TBody.Count; i++)
            {
                var body = TBody[i - 1];
                var bodyPro = body.GetType().GetProperties();
                for (int j = 1; j <= bodyPro.Length; j++)
                {
                    if (bodyPro[j - 1].Name == "Item")
                    {
                        break;
                    }
                    worksheet.Cells[i + 1, j].Value = bodyPro[j - 1].GetValue(body, null);
                }
            }
            return package;

        }
    }
}
